package springboot1706.controller;


import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;


import java.util.List;


import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import com.google.code.kaptcha.impl.DefaultKaptcha;

import springboot1706.bean.User;
import springboot1706.service.UserServiceImpl;



@Controller
@RequestMapping("/userInfo")
public class UserController {
	Logger log = LoggerFactory.getLogger(TestController.class);
	@Autowired
	private UserServiceImpl userServiceImpl;
	@Resource
	private DefaultKaptcha captchaProducer;
	@Resource
	private JavaMailSender mailSender;

  
	/**
	 * 注册用户
	 * @return
	 */
             
	
	
	@RequestMapping("/reg")
	public String reg(HttpServletRequest request,HttpServletResponse response){
		User user = new User();
		user.setUserName(request.getParameter("user"));
		user.setPassWord(request.getParameter("psw"));
		user.setCellphone(request.getParameter("phone"));
		int result = userServiceImpl.insert(user);
		if (result == 1) {
			request.setAttribute("success", "注册成功");
			request.getSession().setAttribute("username",user.getUserName());
			SimpleMailMessage message = new SimpleMailMessage();
    		message.setFrom("1363378049@qq.com");
    		message.setTo("1598328503@qq.com");
    		message.setSubject("主题：简单邮件");
    		message.setText("恭喜您！注册成功！");    
    		mailSender.send(message);

			return "redirect:/userInfo/login";
		} else {
			request.setAttribute("error", "●︿●用户名已存在，请重新注册！");
			return "register";
		}
	}
	@RequestMapping("/register")
	public String register() {
		return "register";
	}
	
	/**
	 * 登录
	 * @return
	 */
	
	@RequestMapping("/login")
	public String login(HttpServletRequest request,User user){
		return "login";
	}
	
	
//	@RequestMapping("dologin")
//	public String login(HttpServletRequest request){
//		User user = new User();
//		user.setUserName(request.getParameter("user"));
//		user.setPassWord(request.getParameter("psw"));
//		User u = userServiceImpl.findUser(user);
//		if (u == null) {
//			request.setAttribute("error","用户名或密码错误");
//			return "login";
//		} else {
//			request.getSession().setAttribute("username",user.getUserName());
//			return "index";
//		}
//	}
	
	
	/**
	 * 后台登录
	 * @return
	 */
	@RequestMapping("/adminlogin")
	public String adminlogin(HttpServletRequest request,HttpServletRequest httpServletRequest,HttpServletResponse httpServletResponse,Model model){
		 String captchaId = (String) request.getSession().getAttribute("vrifyCode");   
         String parameter = request.getParameter("vrifyCode");  
         System.out.println("Session  vrifyCode "+captchaId+" form vrifyCode "+parameter);
         User user = new User();
  		user.setUserName(request.getParameter("user"));
  		user.setPassWord(request.getParameter("psw"));
  		User u = userServiceImpl.findUser(user);
  			if (u==null || !captchaId.equals(parameter)) {  
  	        	model.addAttribute("user", "错误的验证码");  
  	        	return "admin/adminlogin";
  	        
  		}else {  
         	model.addAttribute("user", "正确的验证码"); 
         	return "admin/index";
         }  
	}

	
	
	/**
	 * 退出
	 * @return
	 */
	@RequestMapping("/exit")
	public String exit(HttpServletRequest request){
		request.getSession().removeAttribute("username");
//		response.sendRedirect(request.getHeader("Referer"));
		return "index";
	}
	
	
	/**
	 * 首页
	 * @return
	 */
	@RequestMapping("/index")
	public String index(){
		return "index";
	}
	
	
	 /**
     * 获取验证码 的 请求路径
     * @param request
     * @param response
     * @throws Exception
     */
    @RequestMapping("/defaultKaptcha")  
    public void defaultKaptcha(HttpServletRequest request,HttpServletResponse response) throws Exception{  
            byte[] captchaChallengeAsJpeg = null;    
             ByteArrayOutputStream jpegOutputStream = new ByteArrayOutputStream();    
             try {    
             //生产验证码字符串并保存到session中  
             String createText = captchaProducer.createText();  
             request.getSession().setAttribute("vrifyCode", createText);  
             //使用生产的验证码字符串返回一个BufferedImage对象并转为byte写入到byte数组中  
             BufferedImage challenge = captchaProducer.createImage(createText);  
             ImageIO.write(challenge, "jpg", jpegOutputStream);  
             } catch (IllegalArgumentException e) {    
                 response.sendError(HttpServletResponse.SC_NOT_FOUND);    
                 return;    
             }   

             //定义response输出类型为image/jpeg类型，使用response输出流输出图片的byte数组  
             captchaChallengeAsJpeg = jpegOutputStream.toByteArray();    
             response.setHeader("Cache-Control", "no-store");    
             response.setHeader("Pragma", "no-cache");    
             response.setDateHeader("Expires", 0);    
             response.setContentType("image/jpeg");    
             ServletOutputStream responseOutputStream =    
                     response.getOutputStream();    
             responseOutputStream.write(captchaChallengeAsJpeg);    
             responseOutputStream.flush();    
             responseOutputStream.close();    
    }
    /**
     * 验证的方法
     * @param httpServletRequest
     * @param httpServletResponse
     * @return
     */
    @RequestMapping("/imgvrifyControllerDefaultKaptcha")
    public String  imgvrifyControllerDefaultKaptcha(HttpServletRequest request,HttpServletRequest httpServletRequest,HttpServletResponse httpServletResponse,Model model){  
        
         String captchaId = (String) request.getSession().getAttribute("vrifyCode");   
         String parameter = request.getParameter("vrifyCode");  
         System.out.println("Session  vrifyCode "+captchaId+" form vrifyCode "+parameter);  

        User user = new User();
 		user.setUserName(request.getParameter("user"));
 		user.setPassWord(request.getParameter("psw"));
 		User u = userServiceImpl.findUser(user);
 			if (u==null || !captchaId.equals(parameter) || u.getJinyong()==1) {  
 	        	model.addAttribute("info", "验证码或密码错误");
 	        	return "login";
 		}else {  
 			request.getSession().setAttribute("username",user.getUserName());
 			request.getSession().setAttribute("password",user.getPassWord());
 			request.getSession().setAttribute("sex", u.getGender());
 			request.getSession().setAttribute("address", u.getAddress());
 			request.getSession().setAttribute("cellphone", u.getCellphone());
 			request.getSession().setAttribute("uid", u.getUid());
        	model.addAttribute("user", "正确的验证码"); 
        	return "index";
        }  
    }  
    
    @RequestMapping("/userinfo")
    public String userinfo() {
    	return "userinfo";
    }
    /**
     * 个人信息
     * @param request
     * @return
     */
    @RequestMapping("/myinfo")
    public String myinfo(HttpServletRequest request) {
    	return "myinfo";
    }
    
    @RequestMapping("/updatemyinfo")
    public String updatemyinfo() {
    	return "updatemyinfo";
    }
    
    @RequestMapping("/update")
    public String update(HttpServletRequest request) {
    	User user = new User();
    	user.setUid((Integer)request.getSession().getAttribute("uid"));
		user.setUserName(request.getParameter("username"));
		user.setPassWord(request.getParameter("password"));
		user.setCellphone(request.getParameter("cellphone"));
		user.setGender(request.getParameter("gender"));
    	user.setAddress(request.getParameter("address"));
    	int u = userServiceImpl.update(user);
    	if(u>0) {
    		User u1 = userServiceImpl.getupdate(user);
    		request.getSession().setAttribute("username",user.getUserName());
 			request.getSession().setAttribute("password",user.getPassWord());
 			request.getSession().setAttribute("sex", u1.getGender());
 			request.getSession().setAttribute("address", u1.getAddress());
 			request.getSession().setAttribute("cellphone", u1.getCellphone());
 			request.getSession().setAttribute("uid", u1.getUid());
    		return "redirect:/userInfo/myinfo";
    	}else {
    		return "/update";
    	}
    }
	
}
